<?php
namespace app\common\process;

class GroupBuying extends Automatic {
    protected $model = 'tyyh\\GroupBuying';
    protected $append = ['user', 'sub_number', 'promotion_count_moon'];

    public function add($user) {
        $model    = $this->model;
        $validate = $this->validate;

        $puid = input('post.puid', 0);
        $post = [
            'uid'  => $user['id'],
            'puid' => $puid
        ];
        if(!$validate->scene('add')->check($post)) {
            $this->error($validate->getError());
        }
        try {
            $model->startTrans();
            $result = $model->save($post);
            if($puid) {
                $this->upgrade($puid);
            }
            $openid = loadStorage('Login')->get_openid();
            //$result = $this->profitsharingAdd($openid);
            /*if($result['status'] != 200) {
                throw new \Exception($result['message']);
            }*/
            $model->commit();
        } catch(\Exception $e) {
            $model->rollback();  
            $this->error($e->getMessage());
        }
        return $result;
    }

    public function profitsharingAdd($openid) {
        $url = 'https://xiangcunmaicai.jxoxy.com/api/recharge/profitsharing_add';
        $curl = loadTool('Curl');
        $response = $curl->body($url, ['account' => $openid]);
        return json_decode($response, true);
    }

    public function list($user, $fun = null) {
        $post = input('post.');
        $model = $this->model;
        $validate = $this->validate;

        $uid = $user['id'];
        $model->append($this->append)->where(['puid' => $uid]);

        if(!$validate->scene('search')->check($post)) {
            $this->error($validate->getError());
        }

        if(isset($post['lv'])) {
            $model->where(['lv' => $post['lv']]);
        }

        if(is_callable($fun)) {
            $fun($model);
        }
        return $model->select();
    }

    //升级
    public function upgrade($uid) {
        echo $uid;
        $enum = loadEnum('GroupBuyingLv');
        $model = loadModel('tyyh\\GroupBuying');
        $row = $model->where(['uid' => $uid])->find();
        if(empty($row)) {
            return;
        }

        $zongjian = $enum->code2key('zongjian');
        $jingli = $enum->code2key('jingli');
        $tuanzhang = $enum->code2key('tuanzhang');

        if($model->where('puid', $uid)->where('lv', '>=', $jingli)->count() >= 3) {
            $lv = 2;
        } else if($model->where('puid', $uid)->where('lv', '>=', $tuanzhang)->count() >= 3) {
            $lv = 1;
        } else {
            $lv = 0;
        }

        if($lv > $row['lv']) {
            $row->lv = $lv;
            $row->save();
            if($row['puid']) {
                $this->upgrade($row['puid']);
            }
        }

    }
}
